package com.liuyan.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.SignatureException;

public class MD5 {

    /**
     * 签锟斤拷锟街凤拷锟斤拷
     *
     * @param text          锟斤拷要签锟斤拷锟斤拷锟街凤拷锟斤拷
     * @param key           锟斤拷钥
     * @param input_charset 锟斤拷锟斤拷锟绞?
     * @return 签锟斤拷锟斤拷锟?
     */
    public static String sign(String text, String key, String input_charset) {
        text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * 签锟斤拷锟街凤拷锟斤拷(hbase平台)
     *
     * @param text          锟斤拷要签锟斤拷锟斤拷锟街凤拷锟斤拷
     * @param key           锟斤拷钥
     * @param input_charset 锟斤拷锟斤拷锟绞?
     * @return 签锟斤拷锟斤拷锟?
     */
    public static String signHbase(String text, String key, String input_charset) {
        text = text + "&key=" + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    /**
     * 签锟斤拷锟街凤拷锟斤拷
     *
     * @param text          锟斤拷要签锟斤拷锟斤拷锟街凤拷锟斤拷
     * @param sign          签锟斤拷锟斤拷锟?
     * @param key           锟斤拷钥
     * @param input_charset 锟斤拷锟斤拷锟绞?
     * @return 签锟斤拷锟斤拷锟?
     */
    public static boolean verify(String text, String sign, String key,
                                 String input_charset) {
        text = text + key;
        String mysign = DigestUtils
                .md5Hex(getContentBytes(text, input_charset));
        if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签锟斤拷锟斤拷锟斤拷锟叫筹拷锟街达拷锟斤拷,指锟斤拷锟侥憋拷锟诫集锟斤拷锟斤拷,锟斤拷目前指锟斤拷锟侥憋拷锟诫集锟斤拷:"
                    + charset);
        }
    }

}